<template>
  <a-modal v-model:visible="visible" :title="title" unmount-on-close @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item
        label="角色名称"
        field="name"
        :rules="[
          { required: true, message: '请输入角色名称' },
          { min: 2, max: 10, message: '长度在 2 - 10个字符' }
        ]"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
      >
        <a-input placeholder="请输入角色名称" v-model="form.name" allow-clear></a-input>
      </a-form-item>
      <a-form-item
        label="角色分组"
        field="guard_name"
        :rules="[
          { required: true, message: '请输入角色分组' },
          { min: 2, max: 10, message: '长度在 2 - 10个字符' }
        ]"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
      >
        <a-input disabled placeholder="请输入角色分组" v-model="form.guard_name" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="说明" field="description">
        <a-input placeholder="请输入说明" v-model="form.description" allow-clear></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { roleAdd, roleEdit } from '@/apis'
import { Message } from '@arco-design/web-vue'
const emit = defineEmits(['getTableData'])

const title = computed(() => (form.id ? '编辑角色' : '新增角色'))
const visible = ref(false)
const formRef = ref()

const form = reactive({
  id: undefined,
  name: '',
  guard_name: 'admin',
  description: ''
})

const addOrEdit = (roleItem) => {
  form.id = roleItem?.id || undefined
  form.name = roleItem?.name || ''
  form.guard_name = roleItem?.guard_name || 'admin'
  form.description = roleItem?.description || ''
  visible.value = true
}

const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const api = form.id ? roleEdit : roleAdd
  await api(form)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

defineExpose({ addOrEdit })
</script>
